package com.ruoyi.file.service;

import cn.binarywang.wx.miniapp.bean.WxaCodeUnlimit;
import com.ruoyi.common.core.domain.WxMaCodeVo;
import com.ruoyi.common.wx.config.WxMaConfiguration;
import com.ruoyi.file.utils.FileUploadUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.bytedeco.javacpp.Loader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.text.MessageFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description
 * @Author YangJun
 * @Date 2021年11月19日 11:31:44
 **/
@Service
public class WxFileService {
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;
    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    public void createMaUnLimitCode(WxMaCodeVo vo, HttpServletResponse response) throws WxErrorException, IOException {
        //localFilePath="D://maintenanceTag";
        String prefix = vo.getPrefix();
        Integer length = vo.getLength();
        Integer startNumber = vo.getStartNumber();
        Integer number = vo.getNumber();
        WxaCodeUnlimit wxaCodeUnlimit = new WxaCodeUnlimit();
        wxaCodeUnlimit.setPage("pages/index/index");
        URL bgUrl = new URL(vo.getBgUrl());
        URL logoUrl = new URL(vo.getLogoUrl());
        Double times = vo.getTimes();
        Integer canUseLength = length - prefix.length();
        String fileSrcName = "wxMaCode/" + prefix;
        BufferedImage bgBufImg = ImageIO.read(bgUrl);
        final BufferedImage logoBufImg = ImageIO.read(logoUrl);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (Integer index = startNumber; index <= startNumber + number - 1; index++) {
            BufferedImage thisBgBufImg = new BufferedImage(bgBufImg.getWidth(), bgBufImg.getHeight(), bgBufImg.getType());
            Graphics g = thisBgBufImg.getGraphics();
            g.drawImage(bgBufImg, 0, 0, null);
            g.dispose();
            String scene = prefix + String.format("%0" + canUseLength + "d", index.longValue());
            byte[] bytes = WxMaConfiguration.getMaService().getQrcodeService().createWxaCodeUnlimitBytes(scene, wxaCodeUnlimit.getPage(),
                    wxaCodeUnlimit.getWidth(), wxaCodeUnlimit.isAutoColor(), wxaCodeUnlimit.getLineColor(), wxaCodeUnlimit.isHyaline());
            BufferedImage codeBufImg = ImageIO.read(new ByteArrayInputStream(bytes));
            //将背景读入buffer
            Graphics2D bgGraphics = thisBgBufImg.createGraphics();
            //绘制二维码
            bgGraphics.drawImage(codeBufImg, 34 * times.intValue(), 69 * times.intValue(), 187 * times.intValue(), 187 * times.intValue(), null);
            //绘制编码
            Font font = new Font("Calibri (微软雅黑)", Font.BOLD, 16);
            bgGraphics.setFont(font);
            bgGraphics.setColor(Color.BLACK);
            bgGraphics.drawString(scene, 62 * times.intValue(), 45 * times.intValue());
            //绘制LOGO
            bgGraphics.drawImage(logoBufImg, 85 * times.intValue(), 120 * times.intValue(), 85 * times.intValue(), 85 * times.intValue(), null);
            String fileName = scene + ".png";

            File file = FileUploadUtils.getAbsoluteFile(localFilePath + "/" + fileSrcName + "/", fileName);
            //保存本地
            ImageIO.write(thisBgBufImg, "png", file);
            bgGraphics.dispose();
            zip.putNextEntry(new ZipEntry(fileName));
            IOUtils.write(Files.readAllBytes(file.toPath()), zip);
            zip.flush();
            zip.closeEntry();
        }
        IOUtils.closeQuietly(zip);
        byte[] data = outputStream.toByteArray();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.addHeader("Content-Length", "" + data.length);
        IOUtils.write(data, response.getOutputStream());

    }

    public void createSDSchoolCode(HttpServletResponse response, int weight, int height, int x, int y, String name) throws WxErrorException, IOException, InterruptedException {
        localFilePath = "D://maintenanceTag//school";

        String prefix = "SD";
        Integer length = 10;
        Integer startNumber = 51;
        Integer number = 50;

        WxaCodeUnlimit wxaCodeUnlimit = new WxaCodeUnlimit();
        wxaCodeUnlimit.setPage("pages/index/index");
        File bgFile = new File("D://maintenanceTag//school//dmtbg.jpg");

        Double times = 1D;
        Integer canUseLength = length - prefix.length();
        String fileSrcName = "/schoolCode/" + prefix;
        BufferedImage bgBufImg = ImageIO.read(bgFile);
        System.out.println("_____________________________________________________________________");
        System.out.println(bgBufImg);
        System.out.println("_____________________________________________________________________");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (Integer index = startNumber; index <= startNumber + number - 1; index++) {
            BufferedImage thisBgBufImg = new BufferedImage(bgBufImg.getWidth(), bgBufImg.getHeight(), bgBufImg.getType());
            Graphics g = thisBgBufImg.getGraphics();
            g.drawImage(bgBufImg, 0, 0, null);
            g.dispose();
            String scene = prefix + String.format("%0" + canUseLength + "d", index.longValue());

            File wxFile = WxMaConfiguration.getMaService().getQrcodeService().createQrcode("pages/index/index?scene=" + scene, 280);

            String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
            ProcessBuilder builder =
                    new ProcessBuilder(
                            ffmpeg,
                            "-i",
                            wxFile.getCanonicalPath(),
                            "-vf",
                            MessageFormat.format(
                                    "crop={0}:{1}:{2}:{3}",
                                    String.valueOf(weight),
                                    String.valueOf(height),
                                    String.valueOf(x),
                                    String.valueOf(y)),
                            "-y",
                            localFilePath + fileSrcName + "/temp/"+scene+".jpg");
            builder.inheritIO().start().waitFor();

            File tempCodeFile =new File( localFilePath + fileSrcName + "/temp/"+scene+".jpg");
            File finalCodeFile =new File( localFilePath + fileSrcName + "/final/"+scene+".jpg");
            FileUtils.copyFile(tempCodeFile,finalCodeFile);
            BufferedImage codeBufImg = ImageIO.read(finalCodeFile);
//            try(FileInputStream fis = new FileInputStream(finalCodeFile);
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();){
//                byte[] b = new byte[1024];
//                int n;
//                while ((n = fis.read(b)) != -1)
//                {
//                    bos.write(b, 0, n);
//                }
//
//            }
            //将背景读入buffer
            Graphics2D bgGraphics = thisBgBufImg.createGraphics();
            //绘制二维码
            bgGraphics.drawImage(codeBufImg, 589 * times.intValue(), 150 * times.intValue(), 130 * times.intValue(), 130 * times.intValue(), null);
            //清除不必要的
            bgGraphics.setBackground(Color.WHITE);//设置背景色
            //bgGraphics.clearRect(584, 290, 125, 72);
            bgGraphics.clearRect(584, 280, 125, 82);
            //绘制文字
            Font font = new Font("Calibri (微软雅黑)", Font.BOLD, 30);
            bgGraphics.setFont(font);
            bgGraphics.setColor(Color.RED);
            bgGraphics.drawString("扫码报修", 590 * times.intValue(), 322 * times.intValue());
            String fileName = scene + ".png";


            File file = FileUploadUtils.getAbsoluteFile(localFilePath + "/" + fileSrcName + "/", fileName);
            //保存本地
            ImageIO.write(thisBgBufImg, "png", file);
            bgGraphics.dispose();
            zip.putNextEntry(new ZipEntry(fileName));
            IOUtils.write(Files.readAllBytes(file.toPath()), zip);
            zip.flush();
            zip.closeEntry();
        }
        IOUtils.closeQuietly(zip);
        byte[] data = outputStream.toByteArray();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.addHeader("Content-Length", "" + data.length);
        IOUtils.write(data, response.getOutputStream());

    }
}
